let useraddModule = (function() {
    let $username = $('.username'),
        $spanusername = $('.spanusername'),
        $man = $('#man'),
        $woman = $('#woman'),
        $useremail = $('.useremail'),
        $spanuseremail = $('.spanuseremail'),
        $userphone = $('.userphone'),
        $spanuserphone = $('.spanuserphone'),
        $userdepartment = $('.userdepartment'),
        $userjob = $('.userjob'),
        $userdesc = $('.userdesc'),
        $submit = $('.submit');

    let userId = null,
        isUpdate = false; //判断是修改还是增加
    //先给下拉框添加内容(获取两个下拉框的内容为并行，与整体为串行)
	//parseInt(result.code)：表示当result.code为字符串的时候变为整数
    let selectBind = function() {
        let promise1 = axios.get('/department/list'),
            promise2 = axios.get('/job/list');
        return axios.all([promise1, promise2]).then(results => {
            let [departmentResult, jobResult] = results;
            if (parseInt(departmentResult.code) === 0) {
                let str = ``;
                departmentResult.data.forEach(item => {
                    str += `<option value="${item.id}">${item.name}</option>`;
                })
                $userdepartment.html(str);
            }
            if (parseInt(jobResult.code) === 0) {
                let str = ``;
                jobResult.data.forEach(item => {
                    str += `<option value="${item.id}">${item.name}</option>`;
                })
                $userjob.html(str);
            }
        })


    }

    //点击提交按钮
    let submitHandle = function() {
            $submit.click(function() {
                //1、先表单验证
                if (!checkUserName() || !checkUserEmail() || !checkUserPhone()) return;

                //2、修改和增加是一张表，判断是修改还是增加
                let URL = isUpdate ? '/user/update' : '/user/add';
                axios.post(URL, {
                    userId: isUpdate ? userId : null,
                    name: $username.val().trim(),
                    sex: $woman.prop('checked') ? 1 : 0,
                    email: $useremail.val().trim(),
                    phone: $userphone.val().trim(),
                    departmentId: $userdepartment.val(),
                    jobId: $userjob.val(),
                    desc: $userdesc.val().trim()
                }).then(result => {
                    if (parseInt(result.code) === 0) {
                        alert('当前操作成功，即将返回列表页面', {
                            handled: () => {
                                window.location.href = 'userlist.html'
                            }
                        });
                        return;
                    }
                    return Promise.reject()
                }).catch(reason => {
                    alert('当前操作失败，请稍后重试！')
                })
            })

        }
        //验证用户名
    let checkUserName = function() {
            let usernameVal = $username.val().trim();
            if (usernameVal.length === 0) {
                $spanusername.html(`用户名不能为空，请填写用户名`);
                return false; //验证失败要返回false
            }
            $spanusername.html('');
            return true;
        }
        //验证邮箱
    let checkUserEmail = function() {
            let useremailVal = $useremail.val().trim(),
                reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
            if (useremailVal.length === 0) {
                $spanuseremail.html(`邮箱为必填项，不能为空！`);
                return false;
            }
            if (!reg.test(useremailVal)) {
                $spanuseremail.html(`邮箱为格式不正确！`);
                return false;
            }
            $spanuseremail.html('');
            return true;
        }
        //验证电话号码
    let checkUserPhone = function() {
        let userphoneVal = $userphone.val().trim(),
            reg = /^1\d{10}$/;
        if (userphoneVal.length === 0) {
            $spanuserphone.html(`手机号码为必填项，不能为空！`);
            return false;
        }
        if (!reg.test(userphoneVal)) {
            $spanuserphone.html(`手机号码格式不正确！`);
            return false;
        }
        $spanuserphone.html('');
        return true;
    }

    //展示信息，从服务器获取信息展示在表单中
    let showBaseInfo = function() {
        return axios.get('/user/info', {
            params: {
                userId
            }
        }).then(result => {
            if (parseInt(result.code) === 0) {
                let {
                    name,
                    sex,
                    email,
                    phone,
                    departmentId,
                    jobId,
                    desc
                } = result.data;
                $username.val(name);
                if (parseInt(sex) === 1) {
                    $woman.prop('checked', true);
                }
                $useremail.val(email);
                $userphone.val(phone);
                $userdesc.val(desc);
                $userdepartment.val(departmentId);
                $userjob.val(jobId);
                return;
            }
            return Promise.reject();
        })
    }


    return {
        init() {
            //进入页面先判断该页面是增加还是修改，获取地址栏中问号传参信息，修改的话会携带userId，有就修改，没有就是新增
            let paramsObj = window.location.href.queryURLParams();  //queryURLParams方法解析地址
            if ('userId' in paramsObj) {
                userId = paramsObj.userId;
                isUpdate = true;
            }


            selectBind();
            submitHandle();
            //表单验证，鼠标离开就要验证
            $username.on('blur', checkUserName);
            $useremail.on('blur', checkUserEmail);
            $userphone.on('blur', checkUserPhone);

            //数据处理
            selectBind().then(() => {
                if (isUpdate) {
                    return showBaseInfo();
                }
            }).then(() => {
                submitHandle();
            }).catch(() => {
                alert('当前页面获取相关信息出现问题，请稍后再试！', {
                    handled: () => {
                        window.location.href = 'userlist.html';
                    }
                });

            })
        }
    }
})();

useraddModule.init();